<template>

    <div v-for="item in state" :key="item.id">
        <el-checkbox v-model="item.isCheckAll" :indeterminate="item.isIndeterminate" @change="CheckAllChange(item)">{{
            item.name
        }}</el-checkbox>
        <el-checkbox-group v-model="item.checkeds" @change="CheckedCitiesChange(item)">
            <el-checkbox v-for="city in item.children" :key="city.id" :label="city.id">{{ city.name }}</el-checkbox>
        </el-checkbox-group>
    </div>
    <div>
        <el-button type="primary" @click="clickHandle">保存</el-button>
        <el-button @click="empty">清空</el-button>
    </div>

</template>
<script setup lang='ts'>
import router from '@/router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, watchEffect } from 'vue'
import { useRoute } from 'vue-router';
import { getRourceRoleApi, resourceAllApi, resourceListApi, branchResourceApi } from './api/index'

const route = useRoute()

// 定义总解构
type Istate = (IResourceCategory & {
    children: IRourceRole[],
    checkeds: number[],
    isCheckAll: boolean,
    isIndeterminate: boolean,
})
// 获取的分类,资源,已经勾选的资源，并且过滤数据
let state = ref<Istate[]>()




// 获取id请求该角色已选的资源
if (route.query.id) {
    // 请求全部后台资源和资源分类
    Promise.all([
        resourceAllApi(),
        resourceListApi(),
        getRourceRoleApi(parseInt(route.query.id as string))]).then((res) => {
            state.value = res[0].data.map(item => ({
                ...item,
                children: [],
                checkeds: [],
                isCheckAll: false,
                isIndeterminate: false,
            }))
            res[1].data.forEach(item => {
                const cate = state.value?.find(Item => Item.id === item.categoryId)
                cate && cate.children.push(item)

            });
            res[2].data.forEach(item => {
                const Check = state.value?.find(Item => Item.id === item.categoryId)
                Check && Check.checkeds.push(item.id)
            })
            // state.value.forEach(item => {
            //     item.isCheckAll = item.children.length === item.checkeds.length;
            //     item.isIndeterminate = item.checkeds.length > 0 && item.checkeds.length < item.children.length;
            // })
        }).catch(() => {

        })


}

watchEffect(() => {
    state.value?.forEach(item => {
        item.isCheckAll = item.children.length === item.checkeds.length;
        item.isIndeterminate = item.checkeds.length > 0 && item.checkeds.length < item.children.length;
    })
})


// 点击上键
const CheckAllChange = (data: Istate) => {
    // 判断点击后是否全选,全选就空，反选就全选
    if (!data.isCheckAll) {
        data.checkeds = []
    } else {
        data.checkeds = data.children.map(item => item.id)
    }

    // 判断点击后是否半选
    data.isIndeterminate = data.checkeds.length > 0 && data.checkeds.length < data.children.length

};
// 点击下键
const CheckedCitiesChange = (data: Istate) => {
    // 判断点击后是否全选
    data.isCheckAll = data.checkeds.length === data.children.length ? true : false;


    // 判断点击后是否半选
    data.isIndeterminate = data.checkeds.length > 0 && data.checkeds.length < data.children.length
}

// 点击确定
const clickHandle = () => {
    ElMessageBox.confirm('确定要保存吗', '分配资源', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        branchResourceApi({
            roleId: parseInt(route.query.id as string),
            //获取所有数据，传回后台修改
            resourceIds: state.value?.reduce<number[]>((prev, next) => {
                return prev.concat(next.checkeds);
            }, [])
        }).then((res) => {
            if (res.code === 200) {
                ElMessage.success('保存成功')
                router.push('/ums/role')
            }
        })
    })

}
// 点击清空
const empty = () => {
    state.value?.map(item => item.checkeds = [])

}

</script>
<style lang="less" scoped>

</style>